package com.sailfish.springbootdemo.utils;

import org.apache.tomcat.jni.FileInfo;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class FileConverterUtils {
    public static FileInputStream convertTo(File file) throws IOException {
        return new FileInputStream(file);
    }

    public static FileInputStream convertTo(MultipartFile multipartFile) throws IOException {
        InputStream inputStream = multipartFile.getInputStream();
        return new FileInputStream(getTempFileFromInputStream(inputStream));
    }

    public static File getTempFileFromInputStream(InputStream inputStream) throws IOException {
        File tempFile = File.createTempFile("temp", null);
        tempFile.deleteOnExit();

        // 将输入流的内容写入临时文件
        try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
        }

        return tempFile;
    }

}
